package com.kly.sc.api.integration.im.impl;

import com.kly.sc.api.infras.enums.RestCodeEnum;
import com.kly.sc.api.infras.exception.ApplicationException;
import com.kly.sc.api.integration.im.IMService;
import com.kly.sc.api.integration.im.RCClient;
import com.kly.user.dto.UserAccessDto;
import com.kly.user.service.AuthLoginService;
import io.rong.models.response.TokenResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * 用户IM操作相关类
 * @author linqu
 */
@Service
@Slf4j
public class IMServiceImpl implements IMService {

    @Resource
    RCClient rcClient;
    @Resource
    AuthLoginService authLoginService;

    /**
     * 功能描述: 获取IM Token
     * @param userCode 用户内码
     * @param nickname 名称
     * @param portraitUri 用户头像
     * @return
     */
    @Override
    public String getToken(String userCode, String nickname, String portraitUri) {

        if (StringUtils.isBlank(userCode) || StringUtils.isBlank(nickname) || StringUtils.isBlank(portraitUri)) {
            log.error("The params should not be empty, userCode={} nickname={} portraitUri={}", userCode, nickname, portraitUri);
            throw new ApplicationException(RestCodeEnum.SYSTEM_PARAMETER_ERROR);
        }

        TokenResult tokenResult = rcClient.register(userCode, nickname, portraitUri);
        if (Objects.isNull(tokenResult) || tokenResult.getCode() != 200) {
            log.error("invoke rongCloud server exception,resultCode={},errorMessage={}", tokenResult.getCode(), tokenResult.getErrorMessage());
            throw new ApplicationException(RestCodeEnum.RC_PARAMETER_ERROR + " errorMsg: " + tokenResult.getErrorMessage());
        }
        String token = tokenResult.getToken();

        //根据userId更新本地数据users表中rongCloudToken
        UserAccessDto userAccessDto = buildUserAccessDto(userCode, token);
        authLoginService.saveRongCloudToken(userAccessDto);

        return token;
    }



    private UserAccessDto buildUserAccessDto(String userCode, String token) {
        UserAccessDto userAccessDto = new UserAccessDto();
        userAccessDto.setUserCode(userCode);
        userAccessDto.setToken(token);
        return userAccessDto;
    }
}
